package com.chenzouquan.util.toJson;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

public class YamlToJsonConverter {
    public static String convertYamlToJson(String yamlFilePath) {
        String jsonFilePath = ""; // JSON文件路径

        try {
            // 读取YAML文件内容
            String yamlContent = new String(Files.readAllBytes(Paths.get(yamlFilePath)));

            // 创建Yaml对象并解析YAML内容
            Yaml yaml = new Yaml();
            Map<String, Object> yamlData = yaml.load(yamlContent);

            // 创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 将YAML数据转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(yamlData);

            // 生成临时的JSON文件路径
            jsonFilePath = yamlFilePath.replace(".yaml",".json");

            // 将JSON字符串写入JSON文件
            FileWriter fileWriter = new FileWriter(jsonFilePath);
            fileWriter.write(jsonString);
            fileWriter.close();

            System.out.println("YAML转换为JSON成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 删除原文件
        new File(yamlFilePath).delete();
        return jsonFilePath;
    }
}

